package gui.symbols;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.nio.ByteBuffer;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class SymbolListCellRenderer implements ListCellRenderer{
  
  private static final String PSEUDO[] = 
     {"0", "1", "2", "3", "4", "5", "6", "7", 
      "8", "9", "A", "B", "C", "D", "E", "F"};
  
  public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean cellHasFocus) {
    
    Symbol s = (Symbol)value;
    
    byte[] b = ByteBuffer.wrap(new byte[4]).putInt(s.getField()).array();
    String bytes = byteToString(b);
    
    String name = " " + s.getName();
    JLabel label = new JLabel(" " + bytes + name);
    label.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 11));
    
    if(isSelected){
      label.setBackground(Color.ORANGE);
      label.setOpaque(true);
    }
    
    return label;
  }
  
  private String byteToString(byte[] input){
    StringBuffer out = new StringBuffer(input.length * 3);
    
    for(byte i : input){
      byte l = (byte) (((i & 0xF0) >>> 4) & 0x0F);
      byte r = (byte) (i & 0x0F);
      out.append(PSEUDO[(int)l] + PSEUDO[(int)r] + " ");
    }
    
    return new String(out);
  }
}
